package com.foxmail.yusp75.myexam;

/*
Copyright 2017 Yu shanpeng

*/

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import android.view.View;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.afollestad.materialdialogs.folderselector.FileChooserDialog;
import com.afollestad.materialdialogs.MaterialDialog;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Locale;
import java.util.Objects;

import io.realm.Realm;
import io.realm.RealmQuery;
import io.realm.RealmResults;


public class SettingActivity extends AppCompatActivity implements FileChooserDialog.FileCallback {

    private TextView txt_file, txt_info;
    private EditText txt_paper;
    private Handler handler;
    private Realm realm;

    private ArrayList<String> list;
    private PaperListAdapter adapter;
    private String path;

    private static final int REQUEST_PERMISSION = 10;
    //private static int REQUEST_FILE = 100;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_setting);

        // toolbar
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);

        // ui
        txt_paper = findViewById(R.id.paper);
        txt_info = findViewById(R.id.import_info);

        txt_file = findViewById(R.id.setting_file);
        txt_file.setOnClickListener(view -> {
            if (ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.READ_EXTERNAL_STORAGE)
                    != PackageManager.PERMISSION_GRANTED) {

                ActivityCompat.requestPermissions(SettingActivity.this,
                        new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, REQUEST_PERMISSION);
            } else {
                new FileChooserDialog.Builder(getApplicationContext())
                        .extensionsFilter(".pcm", ".txt")
                        .tag("paper")
                        .show(SettingActivity.this);
            }
        });
        // 题库列表
        ListView listView = findViewById(R.id.list_paper);
        list = new ArrayList<>();
        adapter = new PaperListAdapter(this, listener_del, listener_overview, list);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener((adapterView, view, i, l) -> {
            String paper_selected = list.get(i);

            RealmQuery<Question> query = realm.where(Question.class).equalTo("paper.name",
                    paper_selected);
            long c_item = query.count();
            long c_wrong = query.greaterThan("c_wrong", 0).count();
            long c_bookmark = query.equalTo("bookmark", true).count();

            String info = String.format(Locale.CHINA, "题数：%d，错误数：%d，收藏数：%d",
                    c_item, c_wrong, c_bookmark);
            txt_info.setText(info);
        });

        handler = new Handler();
    }

    @Override
    public void onFileSelection(@NonNull FileChooserDialog dialog, @NonNull File file) {
        path = file.toString();
        String[] file_name = file.getName().split("\\.");

        txt_file.setText(path);
        txt_paper.setText(file_name[0]);
    }

    @Override
    public void onFileChooserDismissed(@NonNull FileChooserDialog dialog) {

    }

    @Override
    protected void onResume() {
        realm = Realm.getDefaultInstance();
        RealmResults<Paper> papers = realm.where(Paper.class).findAll();
        list.clear();
        for (int i = 0; i < papers.size(); i++)
            list.add(papers.get(i).getName());
        adapter.notifyDataSetChanged();

        super.onResume();
    }

    @Override
    protected void onPause() {
        if (realm != null)
            realm.close();
        super.onPause();
    }


    public void btnImportClick(View view) {
        // 导入
        if (path != null && !path.isEmpty())
            new ImportData(getApplicationContext()).execute(path, txt_paper.getText().toString());
    }

    // 类：导入
    private class ImportData extends AsyncTask<String, Integer, Question> {
        private MaterialDialog dialog;
        private final Context context;

        public ImportData(Context context) {
            this.context = context;

        }

        @Override
        protected void onPreExecute() {
            dialog = new MaterialDialog.Builder(SettingActivity.this)
                    .title("导入试题")
                    .content("请稍等。。。")
                    .progress(true, 0)
                    .progressIndeterminateStyle(false).show();

            super.onPreExecute();
        }


        @Override
        protected Question doInBackground(String... values) {

            try {
                InputStream stream = new FileInputStream(values[0]);
                if (values[1].isEmpty()) {
                    handler.post(() -> Toast.makeText(context, "试卷名不能为空", Toast.LENGTH_SHORT).show());
                } else {
                    MainActivity.data(values[1], stream);
                }

            } catch (FileNotFoundException e) {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(context, "错误：文件未找到。", Toast.LENGTH_LONG).show();
                    }
                });
            }
            return null;
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
        }

        @Override
        protected void onCancelled() {
            if (dialog != null)
                dialog.dismiss();

            super.onCancelled();
        }

        @Override
        protected void onPostExecute(Question question) {
            dialog.dismiss();
            super.onPostExecute(question);
            // imported
            list.add(txt_paper.getText().toString());
            txt_file.setText("");
            txt_paper.setText("");
            adapter.notifyDataSetChanged();


        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_PERMISSION) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                new FileChooserDialog.Builder(getApplicationContext())
                        .extensionsFilter(".pcm", ".txt")
                        .tag("paper")
                        .build()
                        .show(SettingActivity.this);
            } else {
                finish();
            }
        }
    }

    private View.OnClickListener listener_del = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            final int idx = (int) v.getTag();
            final String paper = list.get(idx);
            new MaterialDialog.Builder(SettingActivity.this)
                    .title("提示")
                    .content(String.format("确定删除试题：%s？", paper))
                    .positiveText("确定")
                    .negativeText("取消")
                    .onPositive((dialog, which) -> {
                        //Toast.makeText(getApplicationContext(), "deleted !", Toast.LENGTH_SHORT).show();
                        realm.executeTransaction(realm -> {
                            realm.where(Paper.class).equalTo("name", paper).findAll().deleteAllFromRealm();
                            realm.where(Question.class).equalTo("paper.name", paper).findAll().deleteAllFromRealm();
                            list.remove(idx);
                            adapter.notifyDataSetChanged();
                        });

                    })
                    .show();
        }
    };

    private final View.OnClickListener listener_overview = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(SettingActivity.this, PaperViewActivity.class);
            intent.putExtra("paper", list.get((int) v.getTag()));
            startActivity(intent);
        }
    };

    // end
}
